import HttpClient from '../commons/http-client';
import {updateCharge} from '../reducers/charge';
import {FormStatus, updateAppState} from '../reducers/app-state';

export function loadCharge(payload) {
  return async dispatch => {
    const info = {
      page: payload.page ? payload.page : 1,
      page_size: 10,
      search: payload.search ? payload.search : '',
      expand: 'plan',
    };
    const chargeListurl = `/admin/chargerecord?${HttpClient.encodeParams(
      info,
    )}`;
    const chargeStaturl = `/admin/chargerecord/stat?${HttpClient.encodeParams(
      info,
    )}`;
    const chargeListRep = await HttpClient.get(chargeListurl);
    const chargeStatRep = await HttpClient.get(chargeStaturl);
    const data = {
      chargeList: chargeListRep.data.data,
      chargeStat: chargeStatRep.data.data,
    };
    dispatch(updateCharge(data));
  };
}

export function exportCharges(form) {
  return async (dispatch, getState) => {
    const params = {
      ...form,
    };
    try {
      dispatch(updateAppState({formStatus: FormStatus.PENDING}));
      const url = `/admin/chargerecord/export?${HttpClient.encodeParams(
        params,
      )}`;
      const exportRep = await HttpClient.get(url, {responseType: 'blob'});
      const blob = new Blob([exportRep.data]);
      const downloadElement = document.createElement('a');
      const href = window.URL.createObjectURL(blob); // 创建下载的链接
      downloadElement.href = href;
      downloadElement.download = 'exportCSV.csv'; // 下载后文件名
      document.body.appendChild(downloadElement);
      downloadElement.click(); // 点击下载
      document.body.removeChild(downloadElement); // 下载完成移除元素
      window.URL.revokeObjectURL(href); // 释放blob对象
      dispatch(updateAppState({formStatus: FormStatus.SUCCESS}));
    } catch (e) {
      dispatch(updateAppState({formStatus: FormStatus.FAIL}));
      throw e;
    }
  };
}
